import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter表单示例',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const FormDemoPage(),
    );
  }
}

class FormDemoPage extends StatefulWidget {
  const FormDemoPage({Key? key}) : super(key: key);

  @override
  _FormDemoPageState createState() => _FormDemoPageState();
}

class _FormDemoPageState extends State<FormDemoPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _dateController = TextEditingController();

  String? _selectedCity;
  bool _termsAccepted = false;
  String _gender = '男';
  List<String> _interests = [];
  DateTime? _selectedDate;

  final List<String> _cities = ['北京', '上海', '广州', '深圳', '杭州'];
  final List<String> _interestOptions = ['阅读', '旅行', '运动', '音乐', '电影'];

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    _dateController.dispose();
    super.dispose();
  }

  // 日期选择器方法
  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        _dateController.text = DateFormat('yyyy-MM-dd').format(picked);
      });
    }
  }

  // 表单提交方法
  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      if (!_termsAccepted) {
        setState(() {});
        return;
      }
      _formKey.currentState!.save();

      // 收集表单数据
      final formData = {
        'username': _usernameController.text,
        'password': _passwordController.text,
        'email': _emailController.text,
        'phone': _phoneController.text,
        'gender': _gender,
        'interests': _interests,
        'city': _selectedCity,
        'dateOfBirth': _dateController.text,
        'termsAccepted': _termsAccepted,
      };

      // 显示提交成功的对话框
      showDialog(
        context: context,
        builder:
            (context) => AlertDialog(
              title: const Text('表单提交成功'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children:
                    formData.entries.map((entry) {
                      return Text('${entry.key}: ${entry.value}');
                    }).toList(),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('确定'),
                ),
              ],
            ),
      );
    } else {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('表单输入示例')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 用户名输入
              TextFormField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  hintText: '请输入用户名',
                  prefixIcon: Icon(Icons.person),
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  if (value.length < 3) {
                    return '用户名长度至少为3个字符';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16.0),

              // 密码输入
              TextFormField(
                controller: _passwordController,
                decoration: const InputDecoration(
                  labelText: '密码',
                  hintText: '请输入密码',
                  prefixIcon: Icon(Icons.lock),
                  border: OutlineInputBorder(),
                ),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  if (value.length < 6) {
                    return '密码长度至少为6个字符';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16.0),

              // 邮箱输入
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(
                  labelText: '邮箱',
                  hintText: '请输入邮箱',
                  prefixIcon: Icon(Icons.email),
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入邮箱';
                  }
                  if (!RegExp(
                    r'^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$',
                  ).hasMatch(value)) {
                    return '请输入有效的邮箱地址';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16.0),

              // 手机号输入
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  labelText: '手机号',
                  hintText: '请输入手机号',
                  prefixIcon: Icon(Icons.phone),
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入手机号';
                  }
                  if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                    return '请输入有效的手机号';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16.0),

              // 性别选择（单选按钮）
              const Text(
                '性别',
                style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
              ),
              Row(
                children: [
                  Radio(
                    value: '男',
                    groupValue: _gender,
                    onChanged: (value) {
                      setState(() {
                        _gender = value.toString();
                      });
                    },
                  ),
                  const Text('男'),
                  Radio(
                    value: '女',
                    groupValue: _gender,
                    onChanged: (value) {
                      setState(() {
                        _gender = value.toString();
                      });
                    },
                  ),
                  const Text('女'),
                  Radio(
                    value: '其他',
                    groupValue: _gender,
                    onChanged: (value) {
                      setState(() {
                        _gender = value.toString();
                      });
                    },
                  ),
                  const Text('其他'),
                ],
              ),
              const SizedBox(height: 16.0),

              // 兴趣爱好（复选框）
              const Text(
                '兴趣爱好',
                style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
              ),
              Wrap(
                spacing: 8.0,
                children:
                    _interestOptions.map((option) {
                      return ChoiceChip(
                        label: Text(option),
                        selected: _interests.contains(option),
                        onSelected: (selected) {
                          setState(() {
                            if (selected) {
                              _interests.add(option);
                            } else {
                              _interests.removeWhere((item) => item == option);
                            }
                          });
                        },
                      );
                    }).toList(),
              ),
              const SizedBox(height: 16.0),

              // 城市选择（下拉菜单）
              DropdownButtonFormField<String>(
                value: _selectedCity,
                decoration: const InputDecoration(
                  labelText: '所在城市',
                  prefixIcon: Icon(Icons.location_city),
                  border: OutlineInputBorder(),
                ),
                items:
                    _cities.map((city) {
                      return DropdownMenuItem<String>(
                        value: city,
                        child: Text(city),
                      );
                    }).toList(),
                onChanged: (value) {
                  setState(() {
                    _selectedCity = value;
                  });
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请选择所在城市';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16.0),

              // 日期选择
              TextFormField(
                controller: _dateController,
                decoration: InputDecoration(
                  labelText: '出生日期',
                  hintText: '请选择出生日期',
                  prefixIcon: const Icon(Icons.calendar_today),
                  border: const OutlineInputBorder(),
                  suffixIcon: IconButton(
                    icon: const Icon(Icons.date_range),
                    onPressed: () => _selectDate(context),
                  ),
                ),
                readOnly: true,
                onTap: () => _selectDate(context),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请选择出生日期';
                  }
                  CheckboxListTile(
                    title: const Text('我已阅读并同意服务条款和隐私政策'),
                    value: _termsAccepted,
                    onChanged: (value) {
                      setState(() {
                        _termsAccepted = value ?? false;
                      });
                    },
                    controlAffinity: ListTileControlAffinity.leading,
                    contentPadding: EdgeInsets.zero,
                    dense: true,
                  );
                  if (!_termsAccepted)
                    const Padding(
                      padding: EdgeInsets.only(left: 8.0, top: 4.0),
                      child: Text(
                        '请同意服务条款和隐私政策',
                        style: TextStyle(color: Colors.red, fontSize: 12),
                      ),
                    );
                  if (value != true) {
                    return '请同意服务条款和隐私政策';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24.0),

              // 提交按钮
              ElevatedButton(
                onPressed: _submitForm,
                style: ElevatedButton.styleFrom(
                  minimumSize: const Size(double.infinity, 50),
                  textStyle: const TextStyle(fontSize: 18.0),
                ),
                child: const Text('提交表单'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
